﻿using Kevin.Comm.Utility.Crypto;
using Kevin.Shop.Business.Core.Components.Cookie;
using Kevin.Shop.Business.Service.Entity.Helper;
using RiderShop.Mobile.Common.Component;
using RiderShop.Mobile.Common.Helper;
using RiderShop.Mobile.Modle;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace RiderShop.WebSite.Controllers
{
    public partial class CustomerController : ThemeController
    {
        string verifyCodeKey = "VerifyCode";
        public ActionResult VerifyCodeImage()
        {
            string url = ConfigurationManager.AppSettings["DefaultHost"].Trim() + "/VerifyCodeImage.ashx?ref=1&t=" + DateTime.Now.ToString("hhmmss");
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            request.CookieContainer = new CookieContainer();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            string verifyCode = response.Cookies[verifyCodeKey].Value.ToLower();
            KevinCookieManager.Set(FindPasswordModel.VerifyCodeKey, SystemEncrypt.Encrypt(verifyCode));


            return File(response.GetResponseStream(), response.ContentType);
        }

        #region 找回密码
        /// <summary>
        /// 找回密码
        /// </summary>
        /// <returns></returns>
        public ActionResult GetPass()
        {
            FindPasswordModel model = new FindPasswordModel();

            return View(WebClientContext.Current.SiteTheme, "Customer", "GetPass", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
        }

        /// <summary>
        /// 找回密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetPass(FindPasswordModel model)
        {
            if (string.IsNullOrEmpty(model.VerifyCode) || !FindPasswordModel.CheckVerifyCode(model.VerifyCode))
            {
                model.Message = "验证码不正确";
                return View(WebClientContext.Current.SiteTheme, "Customer", "GetPass", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
            }
            if (string.IsNullOrEmpty(model.UserName))
            {
                model.Message = "用户不存在";
                return View(WebClientContext.Current.SiteTheme, "Customer", "GetPass", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
            }
            var userInfo = CacheUsers.Get(model.UserName, true);
            if (userInfo != null && userInfo.UserId > 0)
            {
                return RedirectToAction("GetPassWay", "Customer", new { userName = userInfo.UserName, tk = SystemEncrypt.Encrypt(userInfo.UserName) });
            }
            else
            {
                model.Message = "用户不存在";
            }

            return View(WebClientContext.Current.SiteTheme, "Customer", "GetPass", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
        }
        #endregion

        #region 找回密码的方式
        /// <summary>
        /// 找回密码的方式
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="tk"></param>
        /// <returns></returns>
        public ActionResult GetPassWay(string userName, string tk)
        {
            if (string.IsNullOrEmpty(userName) || SystemEncrypt.Encrypt(userName) != tk)
            {
                return RedirectToAction("GetPass", "Customer");
            }
            var userInfo = CacheUsers.Get(userName, true);
            FindPasswordModel model = new FindPasswordModel();
            model.UserInfo = userInfo;

            return View(WebClientContext.Current.SiteTheme, "Customer", "GetPassWay", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
        }
        
        /// <summary>
        /// 通过邮箱找回
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="tk"></param>
        /// <returns></returns>
        public ActionResult FindPasswordByEmail(string userName, string tk)
        {
            if (string.IsNullOrEmpty(userName) || SystemEncrypt.Encrypt(userName) != tk)
            {
                return RedirectToAction("GetPass", "Customer");
            }

            var userInfo = CacheUsers.Get(userName, true);
            FindPasswordModel model = new FindPasswordModel();
            model.UserInfo = userInfo;
            model.FindPasswordByEmail(userInfo.UserName, userInfo.Email);

            return View(WebClientContext.Current.SiteTheme, "Customer", "FindPasswordByEmail", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
        }

        /// <summary>
        /// 通过手机找回密码
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="tk"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public ActionResult FindPasswordByPhone(string userName, string tk, int action = 0)
        {
            if (!WebClientContext.Current.IsAuthenticated)
            {
                if (string.IsNullOrEmpty(userName) || SystemEncrypt.Encrypt(userName) != tk)
                {
                    return RedirectToAction("GetPass", "Customer");
                }
            }
            else
            {
                userName = WebClientContext.Current.UserName;
            }
            var userInfo = CacheUsers.Get(userName, true);
            FindPasswordModel model = new FindPasswordModel();
            model.UserInfo = userInfo;
            model.ActionType = (FindPasswordAction)action;

            return View(WebClientContext.Current.SiteTheme, "Customer", "FindPasswordByPhone", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
        }

        /// <summary>
        /// 通过手机找回密码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult FindPasswordByPhone(FindPasswordModel model)
        {
            if (string.IsNullOrEmpty(model.UserName) || string.IsNullOrEmpty(model.CellPhone))
            {
                model.Message = "您输入的手机号不正确！";
                return View(WebClientContext.Current.SiteTheme, "Customer", "FindPasswordByPhone", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
            }
            var userInfo = CacheUsers.Get(model.UserName, false);
            model.UserInfo = userInfo;
            //没有登录为找回密码模式，已登录则绑定手机号并可重置密码
            if (model.ActionType == FindPasswordAction.FindPassword)
            {
                if (userInfo.CellPhone != model.CellPhone.Trim())
                {
                    model.Message = "您输入的手机号不正确！";
                    return View(WebClientContext.Current.SiteTheme, "Customer", "FindPasswordByPhone", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
                }
            }
            var response = FindPasswordModel.VefifySMSAuthentiCode(userInfo.UserId, model.VerifyCode);
            if (!response.Status)
            {
                model.Message = response.ErrorMessage;
                return View(WebClientContext.Current.SiteTheme, "Customer", "FindPasswordByPhone", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
            }
            //已登录 绑定新手机号
            if (WebClientContext.Current.IsAuthenticated && (model.ActionType == FindPasswordAction.BindingCellPhone || model.ActionType == FindPasswordAction.SetPassword))
            {
                userInfo.CellPhone = model.CellPhone;
                RiderShop.Mobile.Modle.MyAccount.MyAccountModel.UpdateUser(userInfo);
            }
            if (model.ActionType == FindPasswordAction.BindingCellPhone)
            {
                return RedirectToAction("Home", "MyAccount", new { forgetpwd = response.Tag });
            }
            response = model.FindPasswordByEmail(userInfo.UserName, userInfo.CellPhone);
            if (response.Status)
            {
                return RedirectToAction("ResetPassword", "Customer", new { forgetpwd = response.Tag, action = (int)model.ActionType });
            }
            else
            {
                model.Message = "服务异常，请重试！";
                return View(WebClientContext.Current.SiteTheme, "Customer", "FindPasswordByPhone", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
            }
        }
        #endregion

        #region 发送验证码
        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="cellPhone">手机号码</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SendSMSValdateCode(string userName, string cellPhone)
        {
            if (string.IsNullOrEmpty(userName) || string.IsNullOrWhiteSpace(cellPhone))
            {
                return Json("您输入的手机号不正确！");
            }
            var userInfo = CacheUsers.Get(userName, true);
            if (userInfo == null)
            {
                return Json("您输入的手机号不正确！");
            }
            //没有登录为找回密码模式，已登录则绑定手机号并可重置密码
            if (!WebClientContext.Current.IsAuthenticated)
            {
                if (userInfo.CellPhone != cellPhone.Trim())
                {
                    return Json("您输入的手机号不正确！");
                }
            }
            var response = FindPasswordModel.SendSMSAuthentiCode(userInfo.UserId, cellPhone);
            if (!response.Status)
            {
                return Json(response.ErrorMessage);
            }

            return Json("");
        }
        #endregion

        #region 重置密码
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="forgetpwd"></param>
        /// <returns></returns>
        public ActionResult ResetPassword(string forgetpwd)
        {
            if (string.IsNullOrEmpty(forgetpwd))
            {
                return RedirectToAction("GetPass", "Customer");
            }
            var customer = new CustomerModel();

            return View(WebClientContext.Current.SiteTheme, "Customer", "ResetPassword", WebClientContext.Current.CacheKeyDefaultMasterPage, customer);
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="newPwd"></param>
        /// <param name="forgetpwd"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ResetPassword(string newPwd, string forgetpwd)
        {
            if (string.IsNullOrEmpty(forgetpwd))
            {
                return Json("验证码过期，请重试！");
            }
            var customer = new CustomerModel();
            if (string.IsNullOrEmpty(newPwd) || newPwd.Length < 6 || newPwd.Length > 30)
            {
                return Json("密码长度为6到30！");
            }
            customer.ResetPassword(newPwd, forgetpwd);
            if (WebClientContext.Current.IsAuthenticated)
            {
                var userInfo = WebClientContext.Current.GetCurrentUser();
                if (userInfo.MSN == "weixinfirstlogin")
                {
                    userInfo.MSN = "";//清楚微信注册标记字段
                    RiderShop.Mobile.Modle.MyAccount.MyAccountModel.UpdateUser(userInfo);
                }
            }
            if (customer.Result != null && !customer.Result.Status)
            {
                return Json(customer.Result.ErrorMessage);
            }

            return Json("");
        }
        #endregion
    }
}
